package test.httpclient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;

public class PostMethod {

  /**
   * @param args
   */
  public static void main(String[] args) {
    HttpClient httpclient = new DefaultHttpClient();
    try {
      String keyword = null;

      if (args.length == 0) {
        BufferedReader console = new BufferedReader(new InputStreamReader(System.in));

        System.out.print("Enter keyword: ");
        keyword = console.readLine();
      } else {
        keyword = args[0];
      }

      HttpPost httppost = new HttpPost("http://localhost:8080/demo.servlet/servlet/HttpClientTest");

      MultipartEntity reqEntity = new MultipartEntity();
      reqEntity.addPart("txtKeyword", new StringBody(keyword));

      httppost.setEntity(reqEntity);

      System.out.println("keyword: " + keyword);
      System.out.println("executing request " + httppost.getRequestLine());

      HttpResponse response = httpclient.execute(httppost);
      HttpEntity resEntity = response.getEntity();

      System.out.println("----------------------------------------");
      System.out.println(response.getStatusLine());
      if (resEntity != null) {
        System.out.println("Response content length: " + resEntity.getContentLength());
        System.out.println("Chunked?: " + resEntity.isChunked());
      }
      System.out.println("----------------------------------------");

      BufferedReader content = new BufferedReader(new InputStreamReader(resEntity.getContent()));

      while (content.ready()) {
        System.out.println(content.readLine());
      }
      content.close();
      System.out.println("----------------------------------------");
      if (resEntity != null) {
        resEntity.consumeContent();
      }
    } catch (ClientProtocolException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } finally {
      // When HttpClient instance is no longer needed,
      // shut down the connection manager to ensure
      // immediate deallocation of all system resources
      httpclient.getConnectionManager().shutdown();
    }
  }

}
